// pages/home/home.js
const api = require("../../config/api.js");
const util = require("../../utils/util.js");

Page({
  /**
   * 页面的初始数据
   */
  data: {
    tabbarActive: 0,
    activeTab: 0,
    showDrawer: false,
    showDebugButton: true, // 开发调试用，生产环境应设为 false
    loading: false,
    // 加载锁，防止并发请求
    isLoadingLocked: false,
    // 当前正在加载的tab索引
    loadingTabIndex: null,
    // 标记页面是否已初始化
    isPageInitialized: false,
    selectedService: "car-find-people", // TripSelector 默认选择 - 对应拼车tab
    selectedTrip: "outbound", // TripSelector 默认选择 - 对应拼车tab
    carpoolRequest: {
      address: undefined,
      beginTime: undefined,
      side: undefined,
      type: undefined
    },
    roomRequest: {
      address: undefined,
      beginTime: undefined,
      sex: undefined,
      type: undefined
    },
    ticketRequest: {
      address: undefined,
      beginTime: undefined,
      ticket: undefined,
      type: undefined
    },
    tabs: [
      {
        name: "拼车",
        icon: "/static/icon/carpoolSelect.svg",
        iconInactive: "/static/icon/carpool.svg"
      },
      {
        name: "拼房",
        icon: "/static/icon/roomSelect.svg",
        iconInactive: "/static/icon/room.svg"
      },
      {
        name: "雪票",
        icon: "/static/icon/ticketSelect.svg",
        iconInactive: "/static/icon/ticket.svg"
      }
    ],
    // 弹窗配置 - 根据tab动态显示
    popupConfigs: [
      // 拼车tab配置
      {
        serviceOptions: [
          {
            service: "car-find-people",
            title: "车找人",
            subtitle: "发布拼车信息",
            icon: "https://static.codia.ai/image/2025-10-08/eJ3f6i4okB.png"
          },
          {
            service: "people-find-car",
            title: "人找车",
            subtitle: "发布用车需求",
            icon: "https://static.codia.ai/image/2025-10-08/rv1hf3GEDy.png"
          }
        ],
        selectionTitle: "请选择往返",
        tripOptions: [
          {
            trip: "outbound",
            label: "前往雪场",
            icon: "https://static.codia.ai/image/2025-10-08/R0m03rusQh.png"
          },
          {
            trip: "return",
            label: "雪场返回",
            icon: "https://static.codia.ai/image/2025-10-08/8ngdya59W9.png"
          }
        ],
        targetPage: "carpoolAdd"
      },
      // 拼房tab配置
      {
        serviceOptions: [
          {
            service: "room-find-people",
            title: "房找人",
            subtitle: "发布拼房信息",
            icon: "/static/images/pinfang-fzr.png"
          },
          {
            service: "people-find-room",
            title: "人找房",
            subtitle: "发布用房需求",
            icon: "/static/images/renzhaofang.png"
          }
        ],
        selectionTitle: "请选择要求性别",
        tripOptions: [
          {
            trip: "male",
            label: "要求男",
            icon: "/static/images/man.png"
          },
          {
            trip: "female",
            label: "要求女",
            icon: "/static/images/woman.png"
          }
        ],
        targetPage: "roomSharingAdd"
      },
      // 雪票tab配置
      {
        serviceOptions: [
          {
            service: "ticket-sell",
            title: "转卖",
            subtitle: "发布雪票信息",
            icon: "/static/images/sell.png"
          },
          {
            service: "people-find-ticket",
            title: "求购",
            subtitle: "发布求购需求",
            icon: "/static/images/buy.png"
          }
        ],
        selectionTitle: "请选择票类型",
        tripOptions: [
          {
            trip: "single-day",
            label: "整票",
            icon: "/static/images/zhengpiao.png"
          },
          {
            trip: "multi-day",
            label: "残票",
            icon: "/static/images/canpiao.png"
          }
        ],
        targetPage: "ticketAdd"
      }
    ],
    // 拼车筛选器
    carpoolFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-08/xv6kLuGdSQ.png",
        active: false,
        options: [
          { text: "车找人", value: 0 },
          { text: "人找车", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "往返",
        arrow: "https://static.codia.ai/image/2025-10-08/7zwhU1NJWV.png",
        active: false,
        options: [
          { text: "前往", value: 0 },
          { text: "返回", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "雪场",
        arrow: "https://static.codia.ai/image/2025-10-08/uP1qSWkZm6.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    // 拼房筛选器
    roomFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-08/xv6kLuGdSQ.png",
        active: false,
        options: [
          { text: "房找人", value: 0 },
          { text: "人找房", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "性别",
        arrow: "https://static.codia.ai/image/2025-10-08/7zwhU1NJWV.png",
        active: false,
        options: [
          { text: "男", value: 0 },
          { text: "女", value: 1 }
        ],
        selectedValue: undefined
      },
      {
        text: "雪场",
        arrow: "https://static.codia.ai/image/2025-10-08/uP1qSWkZm6.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    // 雪票筛选器
    ticketFilters: [
      {
        text: "类型",
        arrow: "https://static.codia.ai/image/2025-10-08/xv6kLuGdSQ.png",
        active: false,
        options: [
          { text: "求购", value: 0 },
          { text: "转让", value: 1 }
        ],
        selectedValue: undefined
      },
       {
        text: "整/残",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "整票", value: "0" },
          { text: "残票", value: "1" },
        ],
        selectedValue: undefined
      },
      {
        text: "雪场",
        arrow: "https://static.codia.ai/image/2025-10-08/uP1qSWkZm6.png",
        active: false,
        options: [
          { text: "万龙滑雪场", value: 1 },
          { text: "云顶滑雪场", value: 2 }
        ],
        selectedValue: undefined
      },
      {
        text: "日期",
        arrow: "https://static.codia.ai/image/2025-10-08/ssEap6ePBe.png",
        active: false,
        options: [
          { text: "今天", value: "today" },
          { text: "明天", value: "tomorrow" },
          { text: "后天", value: "day_after_tomorrow" }
        ],
        selectedValue: undefined
      }
    ],
    carpoolCards: [],
    roomSharingCards: [],
    snowTicketCards: [],
    // 分页状态 - 每个tab独立维护
    carpoolPage: 1,
    carpoolPageSize: 10,
    carpoolHasMore: true,
    carpoolTotal: 0,
    roomPage: 1,
    roomPageSize: 10,
    roomHasMore: true,
    roomTotal: 0,
    ticketPage: 1,
    ticketPageSize: 10,
    ticketHasMore: true,
    ticketTotal: 0,
    navItems: [
      {
        name: "广场",
        icon: "https://static.codia.ai/image/2025-10-08/F18Tngjj1L.png"
      },
      {
        name: "进阶",
        icon: "https://static.codia.ai/image/2025-10-08/CqNGgrEjag.png"
      },
      {
        name: "发布",
        icon: "https://static.codia.ai/image/2025-10-08/qbqH6hoyrt.png"
      },
      {
        name: "商城",
        icon: "https://static.codia.ai/image/2025-10-08/6VQQBa08EF.png"
      },
      {
        name: "我的",
        icon: "https://static.codia.ai/image/2025-10-08/KGLOQSy5JC.png"
      }
    ],
    // 公共信息
    publicInfo: null,
    // 轮播图数据
    bannerList: [],
    // ===== 雪场筛选弹窗状态 =====
    showSkiFilter: false, // 底部弹窗（保留）
    skiDropdownOpen: false, // 下拉面板开关
    skiDropdownTop: 0, // 下拉面板顶部定位（数值）
    skiDropdownTopPx: "", // 顶部定位（px字符串），用于wxml style 绑定
    skiCategories: [],
    skiOptionsMap: {},
    skiActiveCategory: "",
    skiSelectedOption: undefined,
    selectedSkiId: null, // 用于回显的雪场ID
    currentSkiOptions: [],
    skiFilterContext: null, // { tab: 0|1|2, filterIndex: number }
    updatingSkiPanel: false, // 控制panel定位的锁，避免多余定位
    // ===== SimpleDropdown组件相关 =====
    simpleDropdownOpen: false, // 简单下拉面板开关
    simpleDropdownTop: 0, // 简单下拉面板顶部定位
    simpleDropdownValue: null, // 当前选中的选项ID，用于回显
    simpleDropdownOptions: [], // 选项列表
    simpleDropdownContext: null, // { tab: 0|1|2, filterIndex: number }
    // ===== DatePicker 渲染数据（避免传入 undefined 覆盖组件默认值）=====
    myMonthLabel: "2025年9月",
    myWeekdays: ["日", "一", "二", "三", "四", "五", "六"],
    myCalendarRows: [
      [
        { label: "27", class: "prev-month" },
        { label: "28", class: "prev-month" },
        { label: "29", class: "prev-month" },
        { label: "30", class: "prev-month" },
        { label: "31", class: "prev-month" },
        { label: "今天", class: "today" },
        { label: "2" }
      ],
      [
        { label: "3" },
        { label: "4" },
        { label: "5" },
        { label: "6" },
        { label: "7" },
        { label: "8" },
        { label: "9" }
      ],
      [
        { label: "10" },
        { label: "11" },
        { label: "12" },
        { label: "13" },
        { label: "14" },
        { label: "15" },
        { label: "16" }
      ],
      [
        { label: "17" },
        { label: "18" },
        { label: "19" },
        { label: "20" },
        { label: "21" },
        { label: "22" },
        { label: "23" }
      ],
      [
        { label: "24" },
        { label: "25" },
        { label: "26" },
        { label: "27" },
        { label: "28" },
        { label: "29" },
        { label: "30" }
      ]
    ]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("Home页面加载完成");
    // 页面加载时获取公共信息和拼车数据（初始加载）
    this.loadPublicInfo();
    this.loadBannerList(); // 加载轮播图数据
    this.loadCarpoolData(false);
    // 标记页面已初始化
    this.setData({
      isPageInitialized: true
    });
  },

  /**
   * 加载轮播图数据（从 GET /index/public_Info 接口获取）
   * @returns {Promise} 返回Promise，用于在刷新时等待完成
   */
  loadBannerList: function () {
    const that = this;
    return util
      .request(api.PublicInfo, {}, "POST", "application/json")
      .then(function (res) {
        console.log("轮播图数据加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 处理轮播图数据
          const imageList = res.data && res.data.imageList ? res.data.imageList : [];
          const bannerList = imageList.map(function (item) {
            return {
              imageUrl: item
            };
          });
          
          that.setData({
            bannerList: bannerList
          });
        } else {
          console.error("轮播图数据加载失败:", res.msg);
        }
      })
      .catch(function (err) {
        console.error("轮播图数据请求失败:", err);
      });
  },

  /**
   * 加载公共信息
   */
  loadPublicInfo: function () {
    const that = this;

    // 加载区域树形数据
    util
      .request(api.RegionTree, {}, "GET", "application/json")
      .then(function (res) {
        console.log("区域树形数据加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 转换树形数据为组件需要的格式
          that.updateSkiDropdownData(res.data);
        } else {
          console.error("区域树形数据加载失败:", res.msg);
        }
      })
      .catch(function (err) {
        console.error("区域树形数据请求失败:", err);
        // 如果新接口失败，尝试使用旧接口作为降级方案
        that.loadPublicInfoFallback();
      });
  },

  /**
   * 降级方案：使用旧的公共信息接口
   */
  loadPublicInfoFallback: function () {
    const that = this;
    util
      .request(api.PublicInfo, {}, "POST", "application/json")
      .then(function (res) {
        console.log("公共信息加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 处理轮播图数据
          const imageList = res.data && res.data.imageList ? res.data.imageList : [];
          const bannerList = imageList.map(function (item) {
            return {
              imageUrl: item.imageUrl || ""
            };
          });
          
          that.setData({
            publicInfo: res.data,
            bannerList: bannerList
          });
          // 更新雪场筛选器选项，同时传递regions数组用于拼房地点筛选
          that.updateSkiResortFilters(res.data.skiList, res.data.regions);
        } else {
          console.error("公共信息加载失败:", res.msg);
        }
      })
      .catch(function (err) {
        console.error("公共信息请求失败:", err);
      });
  },

  /**
   * 更新SkiDropdown组件数据（使用新的树形接口）
   */
  updateSkiDropdownData: function (treeData) {
    if (!treeData || !Array.isArray(treeData) || treeData.length === 0) {
      return;
    }

    // 构建 categories（左侧地区列表）
    const categories = treeData.map(function (region) {
      return {
        id: String(region.id),
        name: region.name
      };
    });

    // 构建 optionsMap（每个地区对应的雪场列表）
    const optionsMap = {};
    treeData.forEach(function (region) {
      if (region.children && Array.isArray(region.children)) {
        optionsMap[String(region.id)] = region.children.map(function (ski) {
          return {
            id: ski.id,
            name: ski.name
          };
        });
      } else {
        optionsMap[String(region.id)] = [];
      }
    });

    // 构建"全部"选项（包含所有雪场）
    const allOptions = [];
    treeData.forEach(function (region) {
      if (region.children && Array.isArray(region.children)) {
        region.children.forEach(function (ski) {
          allOptions.push({
            id: ski.id,
            name: ski.name
          });
        });
      }
    });
    optionsMap["all"] = allOptions;

    // 设置默认选中的地区（第一个）
    const defaultCategory = categories.length > 0 ? categories[0].id : "all";
    const defaultOptions = optionsMap[defaultCategory] || [];
    const defaultSelected =
      defaultOptions.length > 0 ? defaultOptions[0].id : undefined;

    this.setData({
      skiCategories: categories,
      skiOptionsMap: optionsMap,
      skiActiveCategory: defaultCategory,
      skiSelectedOption: defaultSelected
    });

    // 如果有已保存的选中值，尝试回显
    if (this.data.skiSelectedOption) {
      this.setData({
        selectedSkiId: this.data.skiSelectedOption
      });
    }
  },

  /**
   * 更新雪场筛选器选项
   */
  updateSkiResortFilters: function (skiList, regions) {
    if (!skiList || skiList.length === 0) {
      return;
    }

    // 更新拼车筛选器中的雪场选项
    const carpoolFilters = this.data.carpoolFilters;
    const carpoolSkiFilter = carpoolFilters.find(
      (filter) => filter.text === "雪场"
    );
    if (carpoolSkiFilter) {
      carpoolSkiFilter.options = [
        { text: "不限", value: undefined },
        ...skiList.map((ski) => ({ text: ski.name, value: ski.id }))
      ];
    }

    // 更新拼房筛选器中的雪场选项
    const roomFilters = this.data.roomFilters;
    const roomSkiFilter = roomFilters.find((filter) => filter.text === "雪场");
    if (roomSkiFilter) {
      roomSkiFilter.options = [
        { text: "不限", value: undefined },
        ...skiList.map((ski) => ({ text: ski.name, value: ski.id }))
      ];
    }

    // 更新雪票筛选器中的雪场选项
    const ticketFilters = this.data.ticketFilters;
    const ticketSkiFilter = ticketFilters.find(
      (filter) => filter.text === "雪场"
    );
    if (ticketSkiFilter) {
      ticketSkiFilter.options = [
        { text: "不限", value: undefined },
        ...skiList.map((ski) => ({ text: ski.name, value: ski.id }))
      ];
    }

    this.setData({
      carpoolFilters: carpoolFilters,
      roomFilters: roomFilters,
      ticketFilters: ticketFilters
    });

    // 构建雪场弹窗的“全部”选项（其他区域暂无法准确映射时为空）
    const allOptions = (skiList || []).map(function (ski) {
      return { id: ski.id, name: ski.name };
    });

    const initialSelected =
      allOptions && allOptions.length > 0 ? allOptions[0].id : undefined;

    this.setData({
      skiOptionsMap: { ...this.data.skiOptionsMap, all: allOptions },
      skiSelectedOption: initialSelected
    });
  },

  /**
   * 加载拼车数据
   */
  loadCarpoolData: function (isLoadMore) {
    const that = this;

    // 检查当前tab是否为拼车tab，如果不是则跳过
    if (that.data.activeTab !== 0) {
      console.log("当前不是拼车tab，跳过加载");
      return;
    }

    // 如果正在加载且不是加载更多，则跳过
    if (that.data.isLoadingLocked && !isLoadMore) {
      console.log("拼车数据正在加载中，跳过重复请求");
      return;
    }

    // 确定当前页码：如果是加载更多，使用下一页；否则重置为第一页
    let currentPage;
    if (isLoadMore) {
      currentPage = that.data.carpoolPage + 1;
    } else {
      currentPage = 1;
      that.setData({
        carpoolPage: 1,
        carpoolHasMore: true,
        carpoolCards: []
      });
    }

    // 设置加载锁
    that.setData({
      loading: true,
      isLoadingLocked: true,
      loadingTabIndex: 0
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.data.carpoolRequest,
      page: currentPage,
      pageSize: that.data.carpoolPageSize
    };

    util
      .request(api.CarIndex, requestParams, "POST", "application/json")
      .then(function (res) {
        console.log("拼车数据加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 从新的响应格式中获取数据：res.data.records
          const records = res.data && res.data.records ? res.data.records : [];
          const total = res.data && res.data.total ? res.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformCarpoolData(records);

          // 如果是加载更多，追加数据；否则替换数据
          const carpoolCards = isLoadMore
            ? [...that.data.carpoolCards, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = carpoolCards.length < total;

          that.setData({
            carpoolCards: carpoolCards,
            carpoolTotal: total,
            carpoolHasMore: hasMore,
            carpoolPage: currentPage, // 更新页码
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        } else {
          console.error("拼车数据加载失败:", res.msg);
          util.showErrorToast(res.msg || "数据加载失败");
          that.setData({
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        }
      })
      .catch(function (err) {
        console.error("拼车数据请求失败:", err);
        util.showErrorToast("网络请求失败");
        that.setData({
          loading: false,
          isLoadingLocked: false,
          loadingTabIndex: null
        });
      });
  },

  /**
   * 加载雪票数据
   */
  loadSnowTicketData: function (isLoadMore) {
    const that = this;

    // 检查当前tab是否为雪票tab，如果不是则跳过
    if (that.data.activeTab !== 2) {
      console.log("当前不是雪票tab，跳过加载");
      return;
    }

    // 如果正在加载且不是加载更多，则跳过
    if (that.data.isLoadingLocked && !isLoadMore) {
      console.log("雪票数据正在加载中，跳过重复请求");
      return;
    }

    // 确定当前页码：如果是加载更多，使用下一页；否则重置为第一页
    let currentPage;
    if (isLoadMore) {
      currentPage = that.data.ticketPage + 1;
    } else {
      currentPage = 1;
      that.setData({
        ticketPage: 1,
        ticketHasMore: true,
        snowTicketCards: []
      });
    }

    // 设置加载锁
    that.setData({
      loading: true,
      isLoadingLocked: true,
      loadingTabIndex: 2
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.data.ticketRequest,
      page: currentPage,
      pageSize: that.data.ticketPageSize
    };

    util
      .request(api.TicketIndex, requestParams, "POST", "application/json")
      .then(function (res) {
        console.log("雪票数据加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 从新的响应格式中获取数据：res.data.records
          const records = res.data && res.data.records ? res.data.records : [];
          const total = res.data && res.data.total ? res.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformTicketData(records);

          // 如果是加载更多，追加数据；否则替换数据
          const snowTicketCards = isLoadMore
            ? [...that.data.snowTicketCards, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = snowTicketCards.length < total;

          that.setData({
            snowTicketCards: snowTicketCards,
            ticketTotal: total,
            ticketHasMore: hasMore,
            ticketPage: currentPage, // 更新页码
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        } else {
          console.error("雪票数据加载失败:", res.msg);
          util.showErrorToast(res.msg || "数据加载失败");
          that.setData({
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        }
      })
      .catch(function (err) {
        console.error("雪票数据请求失败:", err);
        util.showErrorToast("网络请求失败");
        that.setData({
          loading: false,
          isLoadingLocked: false,
          loadingTabIndex: null
        });
      });
  },

  /**
   * 加载拼房数据
   */
  loadRoomData: function (isLoadMore) {
    const that = this;

    // 检查当前tab是否为拼房tab，如果不是则跳过
    if (that.data.activeTab !== 1) {
      console.log("当前不是拼房tab，跳过加载");
      return;
    }

    // 如果正在加载且不是加载更多，则跳过
    if (that.data.isLoadingLocked && !isLoadMore) {
      console.log("拼房数据正在加载中，跳过重复请求");
      return;
    }

    // 确定当前页码：如果是加载更多，使用下一页；否则重置为第一页
    let currentPage;
    if (isLoadMore) {
      currentPage = that.data.roomPage + 1;
    } else {
      currentPage = 1;
      that.setData({
        roomPage: 1,
        roomHasMore: true,
        roomSharingCards: []
      });
    }

    // 设置加载锁
    that.setData({
      loading: true,
      isLoadingLocked: true,
      loadingTabIndex: 1
    });

    // 构建请求参数，包含分页参数
    const requestParams = {
      ...that.data.roomRequest,
      page: currentPage,
      pageSize: that.data.roomPageSize
    };

    util
      .request(api.RoomIndex, requestParams, "POST", "application/json")
      .then(function (res) {
        console.log("拼房数据加载成功:", res);
        if (String(res.code) === "200" || String(res.code) === "0") {
          // 从新的响应格式中获取数据：res.data.records
          const records = res.data && res.data.records ? res.data.records : [];
          const total = res.data && res.data.total ? res.data.total : 0;

          // 转换API数据为UI数据格式
          const newCards = that.transformRoomData(records);

          // 如果是加载更多，追加数据；否则替换数据
          const roomSharingCards = isLoadMore
            ? [...that.data.roomSharingCards, ...newCards]
            : newCards;

          // 判断是否还有更多数据
          const hasMore = roomSharingCards.length < total;

          that.setData({
            roomSharingCards: roomSharingCards,
            roomTotal: total,
            roomHasMore: hasMore,
            roomPage: currentPage, // 更新页码
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        } else {
          console.error("拼房数据加载失败:", res.msg);
          util.showErrorToast(res.msg || "数据加载失败");
          that.setData({
            loading: false,
            isLoadingLocked: false,
            loadingTabIndex: null
          });
        }
      })
      .catch(function (err) {
        console.error("拼房数据请求失败:", err);
        util.showErrorToast("网络请求失败");
        that.setData({
          loading: false,
          isLoadingLocked: false,
          loadingTabIndex: null
        });
      });
  },

  /**
   * 格式化时间戳为可读日期
   */
  formatDate: function (timestamp) {
    if (!timestamp) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳
      const date =
        timestamp < 10000000000
          ? new Date(timestamp * 1000)
          : new Date(timestamp);

      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        return "";
      }

      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      const dayAfterTomorrow = new Date(
        today.getTime() + 2 * 24 * 60 * 60 * 1000
      );

      const targetDate = new Date(
        date.getFullYear(),
        date.getMonth(),
        date.getDate()
      );

      let prefix = "";
      if (targetDate.getTime() === today.getTime()) {
        prefix = "今天";
      } else if (targetDate.getTime() === tomorrow.getTime()) {
        prefix = "明天";
      } else if (targetDate.getTime() === dayAfterTomorrow.getTime()) {
        prefix = "后天";
      } else {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        const dayNames = [
          "周日",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六"
        ];
        const dayName = dayNames[date.getDay()];
        return `${month}.${day} ${dayName}`;
      }

      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      return `${prefix} ${hours}:${minutes}`;
    } catch (error) {
      console.error("时间格式化失败:", error);
      return "";
    }
  },

  /**
   * 格式化日期和时间（使用goTime字段）
   */
  formatDateWithTime: function (date, goTime) {
    if (!date) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳，或者是日期字符串
      let dateObj;
      if (typeof date === "string") {
        // 如果是日期字符串，如 "2024-01-01"
        dateObj = new Date(date);
      } else {
        dateObj = date < 10000000000 ? new Date(date * 1000) : new Date(date);
      }

      // 验证日期是否有效
      if (isNaN(dateObj.getTime())) {
        return "";
      }

      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
      const dayAfterTomorrow = new Date(
        today.getTime() + 2 * 24 * 60 * 60 * 1000
      );

      const targetDate = new Date(
        dateObj.getFullYear(),
        dateObj.getMonth(),
        dateObj.getDate()
      );

      let prefix = "";
      if (targetDate.getTime() === today.getTime()) {
        prefix = "今天";
      } else if (targetDate.getTime() === tomorrow.getTime()) {
        prefix = "明天";
      } else if (targetDate.getTime() === dayAfterTomorrow.getTime()) {
        prefix = "后天";
      } else {
        const month = dateObj.getMonth() + 1;
        const day = dateObj.getDate();
        const dayNames = [
          "周日",
          "周一",
          "周二",
          "周三",
          "周四",
          "周五",
          "周六"
        ];
        const dayName = dayNames[dateObj.getDay()];
        // 如果有goTime，使用goTime；否则不显示时间
        if (goTime) {
          return `${month}.${day} ${dayName} ${goTime}`;
        }
        return `${month}.${day} ${dayName}`;
      }

      // 如果有goTime，使用goTime；否则使用从日期对象中提取的时间
      const timeStr =
        goTime ||
        `${dateObj.getHours().toString().padStart(2, "0")}:${dateObj
          .getMinutes()
          .toString()
          .padStart(2, "0")}`;
      return `${prefix} ${timeStr}`;
    } catch (error) {
      console.error("时间格式化失败:", error);
      return "";
    }
  },

  /**
   * 转换API数据为UI数据格式
   */
  transformCarpoolData: function (carList) {
    const that = this;
    return carList.map(function (item) {
      // 处理起点显示：如果有locationName，分离主地址和详细地址
      // side=0 (前往): 出发地点用地图，longitude/latitude/locationName 属于出发地点
      const startLocationMain = item.fromAddr || "出发地待定";
      const startLocationDetail = (item.side === 0 && item.locationName) ? item.locationName : null;
      
      // 处理终点显示：如果有locationName，分离主地址和详细地址
      // side=1 (返回): 到达地点用地图，longitude/latitude/locationName 属于到达地点
      const endLocationMain = item.toAddr || "目的地待定";
      const endLocationDetail = (item.side === 1 && item.locationName) ? item.locationName : null;
      
      return {
        id: item.id, // 保留原始ID，用于跳转详情页
        tripType: item.side === 0 ? "outbound" : "return",
        tripTypeText: item.side === 0 ? "前往" : "返回",
        serviceType:
          item.type === 0
            ? "/static/images/chezhaoren.svg"
            : "/static/images/renzhaoche.svg",
        tripTime: that.formatDateWithTime(item.date, item.goTime),
        startLocation: startLocationMain,
        startLocationDetail: startLocationDetail,
        endLocation: endLocationMain,
        endLocationDetail: endLocationDetail,
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-08/z0ouKB6QcC.png",
        userName: item.nickName,
        // status: item.type === 0 ? "可拼" : "求拼",
        peopleCount: item.people + "人",
        boardCount: item.ski > 0 ? item.ski + "板" : "",
        bagCount: item.bag > 0 ? item.bag + "板包" : "",
        price: item.price.toString(),
        peopleIcon: "https://static.codia.ai/image/2025-10-08/L2juZcsFLH.png",
        boardIcon: "https://static.codia.ai/image/2025-10-08/8xYeG5naGc.png",
        bagIcon: "https://static.codia.ai/image/2025-10-08/T41amkDiie.png",
        isClub: item.isClub // 添加isClub字段
      };
    });
  },

  /**
   * 转换雪票API数据为UI数据格式
   */
  transformTicketData: function (ticketList) {
    const that = this;
    return ticketList.map(function (item) {
      return {
        id: item.id,
        type: item.type === 0 ? "求购" : "转卖",
        ticketType: item.ticketType === 0 ? "残票" : "整票",
        dateTime: that.formatTicketDateTime(item.date, item.ticket),
        location: item.skiAddress || "", // 直接使用skiAddress字段
        isFull: item.isFull,
        detail: item.detail || "",
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-19/S0NzN69kEs.png",
        userName: item.nickName || "昵称文字",
        quantity: item.count + "张",
        duration: that.getDurationText(item.ticketType),
        delivery: that.getDeliveryText(item.getType),
        price: item.price.toString(),
        locationIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/x7vFQxgM9d.png"
            : "https://static.codia.ai/image/2025-10-19/GBAadCr77k.png",
        meetingIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/DsfqyDAgqc.png"
            : "https://static.codia.ai/image/2025-10-19/tneTxFyDuy.png",
        quantityIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/Ehi0T29ULU.png"
            : "https://static.codia.ai/image/2025-10-19/JfxuZgK0vd.png",
        durationIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/AR4zf0WytE.png"
            : "https://static.codia.ai/image/2025-10-19/WKtTdETv5p.png",
        deliveryIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/6eThc7noKN.png"
            : "https://static.codia.ai/image/2025-10-19/JQjigRpbqp.png",
        isClub: item.isClub
      };
    });
  },

  /**
   * 格式化雪票日期时间
   */
  formatTicketDateTime: function (date, ticket) {
    if (!date) {
      return "";
    }

    try {
      // 固定为毫秒级时间戳
      const dateObj = new Date(date);

      // 验证日期是否有效
      if (isNaN(dateObj.getTime())) {
        return "";
      }

      const month = dateObj.getMonth() + 1;
      const day = dateObj.getDate();
      const dayNames = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const dayName = dayNames[dateObj.getDay()];

      // 根据ticket字段确定时间段
      let timeSlot = "上午";
      if (ticket === "1" || ticket === 1) {
        timeSlot = "上午";
      } else if (ticket === "2" || ticket === 2) {
        timeSlot = "下午";
      } else if (ticket === "3" || ticket === 3) {
        timeSlot = "夜场";
      } else if (ticket === "0" || ticket === 0) {
        timeSlot = "全天";
      }

      return `${month}.${day} ${dayName} ${timeSlot}`;
    } catch (error) {
      console.error("日期格式化失败:", error);
      return "";
    }
  },

  /**
   * 获取会面信息文本
   */
  getMeetingInfo: function (getType) {
    const meetingMap = {
      0: "面交",
      1: "线上"
    };
    return meetingMap[getType] || "面交";
  },

  /**
   * 获取时长文本
   */
  getDurationText: function (ticketType) {
    const durationMap = {
      0: "1日",
      1: "1.5日",
      2: "2日",
      3: "多日"
    };
    return durationMap[ticketType] || "1.5日";
  },

  /**
   * 获取交付方式文本
   */
  getDeliveryText: function (getType) {
    const deliveryMap = {
      0: "面交",
      1: "线上"
    };
    return deliveryMap[getType] || "面交";
  },

  /**
   * 转换拼房API数据为UI数据格式
   */
  transformRoomData: function (roomList) {
    const that = this;
    return roomList.map(function (item) {
      return {
        id: item.id,
        type: item.type === 0 ? "room-seeking" : "person-seeking",
        typeText: item.type === 0 ? "房找人" : "人找房",
        dateRange: that.formatDateRange(item.beginTime, item.endTime),
        duration: that.calculateDuration(item.beginTime, item.endTime),
        hotelIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/mb9v9tEaFF.png"
            : "https://static.codia.ai/image/2025-10-19/sJWUhHWs5J.png",
        hotelName: item.address || "酒店信息待完善",
        skiResortIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/9Y9p75bNgy.png"
            : "https://static.codia.ai/image/2025-10-19/FyonST16C3.png",
        skiResortName: item.skiAddress || "", // 直接使用skiAddress字段
        userAvatar:
          item.imageUrl ||
          "https://static.codia.ai/image/2025-10-19/TW0gtYHhM5.png",
        userName: item.nickName || "昵称文字",
        skiLodgeIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/Xuz9Y3TgZS.png"
            : "https://static.codia.ai/image/2025-10-19/PwnjX2PR6s.png",
        skiLodge: item.ski === 0 ? "单房" : "住滑",
        bedTypeIcon:
          item.type === 0
            ? "https://static.codia.ai/image/2025-10-19/ZKrzQQ9N6N.png"
            : "https://static.codia.ai/image/2025-10-19/ojB4h4j7De.png",
        bedType: that.getBedTypeText(item.homeType),
        genderIcon:
          item.limitSex === 0
            ? "https://static.codia.ai/image/2025-10-19/RTn4SkXmeP.png"
            : "https://static.codia.ai/image/2025-10-19/bHpck7WcLw.png",
        genderRequirement: item.limitSex === 0 ? "男" : "女",
        price: item.price.toString(),
        isClub: item.isClub
      };
    });
  },

  /**
   * 格式化日期范围
   */
  formatDateRange: function (beginTime, endTime) {
    if (!beginTime || !endTime) {
      return "12.22周三-12.30周四"; // 默认值
    }

    // 格式化开始时间
    const beginStr = this.formatDateForDisplay(beginTime);
    // 格式化结束时间
    const endStr = this.formatDateForDisplay(endTime);

    return `${beginStr}-${endStr}`;
  },

  /**
   * 格式化时间为显示格式
   */
  formatDateForDisplay: function (timestamp) {
    if (!timestamp) return "";

    try {
      // 判断是秒级时间戳还是毫秒级时间戳
      const date =
        timestamp < 10000000000
          ? new Date(timestamp * 1000)
          : new Date(timestamp);

      // 验证日期是否有效
      if (isNaN(date.getTime())) {
        return "";
      }

      const month = date.getMonth() + 1;
      const day = date.getDate();
      const dayNames = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
      const dayName = dayNames[date.getDay()];

      return `${month}.${day}${dayName}`;
    } catch (error) {
      console.error("日期格式化失败:", error);
      return "";
    }
  },

  /**
   * 计算住宿天数
   */
  calculateDuration: function (beginTime, endTime) {
    if (!beginTime || !endTime) {
      return ""; // 如果没有时间信息，返回空字符串
    }

    try {
      let begin, end;

      // 处理开始时间
      if (typeof beginTime === "string" && beginTime.includes("-")) {
        // 日期字符串格式，如 "2024-12-22"
        begin = new Date(beginTime);
      } else {
        // 时间戳格式（可能是秒级或毫秒级）
        const beginTimestamp =
          typeof beginTime === "string" ? parseFloat(beginTime) : beginTime;
        begin =
          beginTimestamp < 10000000000
            ? new Date(beginTimestamp * 1000)
            : new Date(beginTimestamp);
      }

      // 处理结束时间
      if (typeof endTime === "string" && endTime.includes("-")) {
        // 日期字符串格式，如 "2024-12-22"
        end = new Date(endTime);
      } else {
        // 时间戳格式（可能是秒级或毫秒级）
        const endTimestamp =
          typeof endTime === "string" ? parseFloat(endTime) : endTime;
        end =
          endTimestamp < 10000000000
            ? new Date(endTimestamp * 1000)
            : new Date(endTimestamp);
      }

      // 验证日期是否有效
      if (isNaN(begin.getTime()) || isNaN(end.getTime())) {
        console.warn("无效的日期:", beginTime, endTime);
        return "";
      }

      // 计算日期差（按天计算，不考虑具体时间）
      const beginDate = new Date(
        begin.getFullYear(),
        begin.getMonth(),
        begin.getDate()
      );
      const endDate = new Date(
        end.getFullYear(),
        end.getMonth(),
        end.getDate()
      );
      const diffTime = endDate.getTime() - beginDate.getTime();
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));

      if (diffDays <= 0) {
        return "";
      }

      return `| ${diffDays}晚`;
    } catch (error) {
      console.error("计算住宿天数失败:", error);
      return "";
    }
  },

  /**
   * 获取床型文本
   */
  getBedTypeText: function (homeType) {
    const bedTypeMap = {
      0: "双床",
      1: "大床",
      2: "单床"
    };
    return bedTypeMap[homeType] || "双床";
  },

  /**
   * 根据雪场ID获取雪场名称
   */
  getSkiResortName: function (skiResortId) {
    if (!this.data.publicInfo || !this.data.publicInfo.skiList) {
      return "万龙滑雪场"; // 默认值
    }

    const skiResort = this.data.publicInfo.skiList.find(
      (ski) => ski.id === skiResortId
    );
    return skiResort ? skiResort.name : "万龙滑雪场";
  },

  /**
   * 更新拼车请求参数
   */
  updateCarpoolRequest: function (params) {
    const that = this;
    const updatedRequest = { ...that.data.carpoolRequest };

    // 只更新非undefined的字段，undefined表示要清空字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        // 清空该字段
        delete updatedRequest[key];
      } else {
        updatedRequest[key] = params[key];
      }
    });

    that.setData({
      carpoolRequest: updatedRequest
    });
    // 重新加载数据（重置分页）
    that.loadCarpoolData(false);
  },

  /**
   * 更新拼房请求参数
   */
  updateRoomRequest: function (params) {
    const that = this;
    const updatedRequest = { ...that.data.roomRequest };

    // 只更新非undefined的字段，undefined表示要清空字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        // 清空该字段
        delete updatedRequest[key];
      } else {
        updatedRequest[key] = params[key];
      }
    });

    that.setData({
      roomRequest: updatedRequest
    });
    // 重新加载数据（重置分页）
    that.loadRoomData(false);
  },

  /**
   * 更新雪票请求参数
   */
  updateTicketRequest: function (params) {
    const that = this;
    const updatedRequest = { ...that.data.ticketRequest };

    // 只更新非undefined的字段，undefined表示要清空字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        // 清空该字段
        delete updatedRequest[key];
      } else {
        updatedRequest[key] = params[key];
      }
    });

    that.setData({
      ticketRequest: updatedRequest
    });
    // 重新加载数据（重置分页）
    that.loadSnowTicketData(false);
  },

  /**
   * Tab点击事件
   */
  onTabClick: function (e) {
    const index = e.currentTarget.dataset.index;
    const currentConfig = this.data.popupConfigs[index];

    // 切换tab时关闭雪场筛选、简单下拉和日期筛选组件
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    // 切换tab时滚动到页面顶部，解决切换闪动问题
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0 // 立即滚动，无动画
    });

    // 重置所有筛选条件
    this.resetCarpoolFilters();
    this.resetRoomFilters();
    this.resetTicketFilters();

    // 重置请求参数
    this.updateCarpoolRequest({
      address: undefined,
      beginTime: undefined,
      side: undefined,
      type: undefined
    });
    this.updateRoomRequest({
      address: undefined,
      beginTime: undefined,
      sex: undefined,
      type: undefined
    });
    this.updateTicketRequest({
      address: undefined,
      beginTime: undefined,
      isFull: undefined,
      type: undefined
    });

    // 如果切换到的tab与当前tab相同，则不执行任何操作
    if (this.data.activeTab === index) {
      console.log("切换到相同tab，跳过操作");
      return;
    }

    // 如果正在加载其他tab的数据，先释放锁
    if (this.data.isLoadingLocked && this.data.loadingTabIndex !== index) {
      console.log("检测到其他tab正在加载，释放锁并切换tab");
      this.setData({
        isLoadingLocked: false,
        loadingTabIndex: null,
        loading: false
      });
    }

    this.setData({
      activeTab: index,
      // 重置为当前tab的默认选择
      selectedService: currentConfig.serviceOptions[0].service,
      selectedTrip: currentConfig.tripOptions[0].trip
    });
    console.log("Tab点击:", this.data.tabs[index].name);

    // 根据tab切换加载对应数据（重置分页）
    // 使用setTimeout确保setData完成后再加载数据
    setTimeout(() => {
      if (index === 0) {
        // 拼车tab
        this.loadCarpoolData(false);
      } else if (index === 1) {
        // 拼房tab
        this.loadRoomData(false);
      } else if (index === 2) {
        // 雪票tab
        this.loadSnowTicketData(false);
      }
    }, 0);
  },

  /**
   * 重置拼车筛选器状态
   */
  resetCarpoolFilters: function () {
    const filters = this.data.carpoolFilters;
    const originalTexts = ["类型", "往返", "雪场", "日期"];

    filters.forEach((filter, index) => {
      filter.active = false;
      filter.selectedValue = undefined;
      filter.text = originalTexts[index];
    });

    this.setData({
      carpoolFilters: filters
    });
  },

  /**
   * 重置拼房筛选器状态
   */
  resetRoomFilters: function () {
    const filters = this.data.roomFilters;
    const originalTexts = ["类型", "性别", "雪场", "日期"];

    filters.forEach((filter, index) => {
      filter.active = false;
      filter.selectedValue = undefined;
      filter.text = originalTexts[index];
    });

    this.setData({
      roomFilters: filters
    });
  },

  /**
   * 重置雪票筛选器状态
   */
  resetTicketFilters: function () {
    const filters = this.data.ticketFilters;
    const originalTexts = ["类型", "整/残", "雪场", "日期"];

    filters.forEach((filter, index) => {
      filter.active = false;
      filter.selectedValue = undefined;
      filter.text = originalTexts[index];
    });

    this.setData({
      ticketFilters: filters
    });
  },

  /**
   * 拼车筛选器点击事件
   */
  onCarpoolFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 0, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、往返筛选 - 使用SimpleDropdown组件
      this.showCarpoolFilterOptions(index);
    }
  },

  /**
   * 拼房筛选器点击事件
   */
  onRoomFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 1, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、性别筛选 - 使用SimpleDropdown组件
      this.showRoomFilterOptions(index);
    }
  },

  /**
   * 雪票筛选器点击事件
   */
  onTicketFilterClick: function (e) {
    const index = e.currentTarget.dataset.index;

    // 关闭其他下拉框
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }

    if (index === 2) {
      // 雪场筛选 - 使用SkiDropdown组件
      this.openSkiFilterPopup({ tab: 2, filterIndex: index });
    } else if (index === 3) {
      // 日期筛选 - 使用DatePicker组件
      const that = this;
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;
          that.setData({ datePickerOpen: true, datePickerTop: top });
        });
    } else {
      // 类型、时段筛选 - 使用SimpleDropdown组件
      this.showTicketFilterOptions(index);
    }
  },

  // ===== 雪场筛选弹窗：打开/关闭与交互 =====
  /**
   * 刷新雪场弹窗panel 位置，始终贴住.filter-section的底部
   */
  updateSkiDropdownPanelPosition: function () {
    if (!this.data.skiDropdownOpen) return;
    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect(function (rect) {
        if (!that.data.skiDropdownOpen || !rect) return;
        const topVal = rect.top + rect.height;
        that.setData({
          skiDropdownTop: topVal,
          skiDropdownTopPx: topVal + "px"
        });
      })
      .exec();
  },
  closeDatePicker: function () {
    this.setData({ datePickerOpen: false });
  },

  // DatePicker 事件：重置/选择/确认/翻月
  onDateReset: function () {
    const activeTab = this.data.activeTab;
    if (activeTab === 0) {
      const filters = this.data.carpoolFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ carpoolFilters: filters });
      this.updateCarpoolRequest({ beginTime: undefined });
    } else if (activeTab === 1) {
      const filters = this.data.roomFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ roomFilters: filters });
      this.updateRoomRequest({ beginTime: undefined });
    } else if (activeTab === 2) {
      const filters = this.data.ticketFilters;
      filters[3].text = "日期";
      filters[3].active = false;
      filters[3].selectedValue = undefined;
      this.setData({ ticketFilters: filters });
      this.updateTicketRequest({ beginTime: undefined });
    }
  },
  onDateSelect: function (e) {
    // 单个日期选择，无需即时刷新列表
  },
  onDateConfirm: function (e) {
    // single 模式：{ value }
    const selectedDate = e.detail && e.detail.value;
    const activeTab = this.data.activeTab;

    // 生成显示文案，如 12.22
    const label = this.formatDateLabel(selectedDate);

    if (activeTab === 0) {
      // 拼车：使用单个日期作为 beginTime
      const filters = this.data.carpoolFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ carpoolFilters: filters });
      // 使用 applyCarpoolFilters 统一处理所有筛选条件，确保日期格式正确
      this.applyCarpoolFilters();
    } else if (activeTab === 1) {
      // 拼房：使用单个日期
      const filters = this.data.roomFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ roomFilters: filters });
      // 使用 applyRoomFilters 统一处理所有筛选条件，确保日期格式正确
      this.applyRoomFilters();
    } else if (activeTab === 2) {
      // 雪票：使用单个日期
      const filters = this.data.ticketFilters;
      filters[3].text = label || "日期";
      filters[3].active = !!selectedDate;
      filters[3].selectedValue = selectedDate;
      this.setData({ ticketFilters: filters });
      // 使用 applyTicketFilters 统一处理所有筛选条件，确保日期格式正确
      this.applyTicketFilters();
    }

    this.closeDatePicker();
  },
  prevMonth: function () {},
  nextMonth: function () {},

  // 工具：显示单个日期文案
  formatDateLabel: function (date) {
    if (!date) return "";
    return this.formatForPickerTag(date);
  },
  formatForPickerTag: function (dateStr) {
    try {
      const d = new Date(dateStr);
      const m = String(d.getMonth() + 1);
      const day = String(d.getDate());
      return m + "." + day;
    } catch (_) {
      return dateStr;
    }
  },

  openSkiFilterPopup: function (context) {
    // toggle: 已打开且是当前同一个tab和filterIndex，直接关闭
    if (
      this.data.skiDropdownOpen &&
      this.data.skiFilterContext &&
      this.data.skiFilterContext.tab === context.tab &&
      this.data.skiFilterContext.filterIndex === context.filterIndex
    ) {
      this.closeSkiDropdown();
      return;
    }

    // 获取当前tab的筛选器中已选中的雪场ID（用于回显）
    // 注意：直接通过 filterIndex 获取，而不是通过 text 查找（因为选择后 text 会变成雪场名称）
    let selectedSkiId = null;
    if (context.tab === 0) {
      // 拼车tab
      const carpoolFilters = this.data.carpoolFilters || [];
      const skiFilter = carpoolFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    } else if (context.tab === 1) {
      // 拼房tab
      const roomFilters = this.data.roomFilters || [];
      const skiFilter = roomFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    } else if (context.tab === 2) {
      // 雪票tab
      const ticketFilters = this.data.ticketFilters || [];
      const skiFilter = ticketFilters[context.filterIndex];
      if (
        skiFilter &&
        skiFilter.selectedValue !== undefined &&
        skiFilter.selectedValue !== null
      ) {
        selectedSkiId = skiFilter.selectedValue;
      }
    }

    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect()
      .exec(function (res) {
        const rect = res && res[0];
        const top = rect ? rect.top + rect.height : 100;
        that.setData({
          skiDropdownOpen: true,
          skiDropdownTop: top,
          skiFilterContext: context,
          selectedSkiId: selectedSkiId // 传入组件用于回显
        });
      });
  },

  closeSkiDropdown: function () {
    this.setData({ skiDropdownOpen: false, updatingSkiPanel: false });
  },

  /**
   * 页面滚动时，关闭所有下拉框
   */
  onPageScroll: function () {
    if (this.data.skiDropdownOpen) {
      this.closeSkiDropdown();
    }
    if (this.data.simpleDropdownOpen) {
      this.closeSimpleDropdown();
    }
    if (this.data.datePickerOpen) {
      this.closeDatePicker();
    }
  },

  /**
   * 刷新SimpleDropdown panel位置，始终贴住.filter-section的底部
   */
  updateSimpleDropdownPanelPosition: function () {
    if (!this.data.simpleDropdownOpen) return;
    const that = this;
    wx.createSelectorQuery()
      .select(".filter-section")
      .boundingClientRect()
      .exec(function (res) {
        const rect = res && res[0];
        if (!that.data.simpleDropdownOpen || !rect) return;
        const topVal = rect.top + rect.height;
        that.setData({
          simpleDropdownTop: topVal
        });
      });
  },

  /**
   * SkiDropdown组件change事件处理（单选模式）
   */
  onSkiDropdownChange: function (e) {
    const optionId = e.detail.value;
    const optionName = e.detail.name;
    const ctx = this.data.skiFilterContext;

    if (!ctx) {
      this.closeSkiDropdown();
      return;
    }

    // 处理"不限"选项：optionId为null、undefined或空字符串时重置
    const isReset =
      optionId === null || optionId === undefined || optionId === "";

    // 根据当前 tab 更新对应的 filters
    if (ctx.tab === 0) {
      const filters = this.data.carpoolFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      filters[ctx.filterIndex].text = isReset ? "雪场" : optionName;
      this.setData({
        carpoolFilters: filters,
        selectedSkiId: isReset ? null : optionId // 更新选中值用于回显
      });
      this.applyCarpoolFilters();
    } else if (ctx.tab === 1) {
      const filters = this.data.roomFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      filters[ctx.filterIndex].text = isReset ? "雪场" : optionName;
      this.setData({
        roomFilters: filters,
        selectedSkiId: isReset ? null : optionId // 更新选中值用于回显
      });
      this.applyRoomFilters();
    } else if (ctx.tab === 2) {
      const filters = this.data.ticketFilters;
      filters[ctx.filterIndex].selectedValue = isReset ? undefined : optionId;
      filters[ctx.filterIndex].active = !isReset;
      filters[ctx.filterIndex].text = isReset ? "雪场" : optionName;
      this.setData({
        ticketFilters: filters,
        selectedSkiId: isReset ? null : optionId // 更新选中值用于回显
      });
      this.applyTicketFilters();
    }
  },

  /**
   * SimpleDropdown组件change事件处理
   */
  onSimpleDropdownChange: function (e) {
    const optionId = e.detail.value;
    const optionName = e.detail.name;
    const ctx = this.data.simpleDropdownContext;

    if (!ctx) {
      this.closeSimpleDropdown();
      return;
    }

    // 处理"不限"选项：optionId为null、undefined时重置
    const isReset =
      optionId === null || optionId === undefined || optionId === "";

    // 根据当前 tab 更新对应的 filters
    if (ctx.tab === 0) {
      // 拼车tab
      const filters = this.data.carpoolFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        // 重置逻辑：清空选中值，恢复原始文本
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "往返", "雪场", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          carpoolFilters: filters
        });

        // 应用拼车筛选条件
        this.applyCarpoolFilters();

        // 选中后关闭下拉框
        this.closeSimpleDropdown();
      } else {
        // 找到对应的option
        const option = filter.options.find((opt) => {
          // 注意：value可能是数字或字符串类型
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            carpoolFilters: filters
          });

          // 应用拼车筛选条件
          this.applyCarpoolFilters();

          // 选中后关闭下拉框
          this.closeSimpleDropdown();
        }
      }
    } else if (ctx.tab === 1) {
      // 拼房tab
      const filters = this.data.roomFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        // 重置逻辑：清空选中值，恢复原始文本
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "性别", "雪场", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          roomFilters: filters
        });

        // 应用拼房筛选条件
        this.applyRoomFilters();

        // 选中后关闭下拉框
        this.closeSimpleDropdown();
      } else {
        // 找到对应的option
        const option = filter.options.find((opt) => {
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            roomFilters: filters
          });

          // 应用拼房筛选条件
          this.applyRoomFilters();

          // 选中后关闭下拉框
          this.closeSimpleDropdown();
        }
      }
    } else if (ctx.tab === 2) {
      // 雪票tab
      const filters = this.data.ticketFilters;
      const filter = filters[ctx.filterIndex];

      if (isReset) {
        // 重置逻辑：清空选中值，恢复原始文本
        filters[ctx.filterIndex].selectedValue = undefined;
        filters[ctx.filterIndex].active = false;
        const originalTexts = ["类型", "整/残", "雪场", "日期"];
        filters[ctx.filterIndex].text = originalTexts[ctx.filterIndex];

        this.setData({
          ticketFilters: filters
        });

        // 应用雪票筛选条件
        this.applyTicketFilters();

        // 选中后关闭下拉框
        this.closeSimpleDropdown();
      } else {
        // 找到对应的option
        const option = filter.options.find((opt) => {
          // 注意：时段筛选的value可能是字符串类型
          return (
            opt.value === optionId || String(opt.value) === String(optionId)
          );
        });

        if (option) {
          filters[ctx.filterIndex].selectedValue = option.value;
          filters[ctx.filterIndex].active = true;
          filters[ctx.filterIndex].text = option.text;

          this.setData({
            ticketFilters: filters
          });

          // 应用雪票筛选条件
          this.applyTicketFilters();

          // 选中后关闭下拉框
          this.closeSimpleDropdown();
        }
      }
    }
  },

  /**
   * 关闭SimpleDropdown组件
   */
  closeSimpleDropdown: function () {
    this.setData({
      simpleDropdownOpen: false
    });
  },

  /**
   * 显示拼车筛选选项 - 使用SimpleDropdown组件
   */
  showCarpoolFilterOptions: function (filterIndex) {
    const filter = this.data.carpoolFilters[filterIndex];

    // 如果已经打开且是同一个筛选项，直接关闭（toggle）
    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 0 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    // 将options转换为SimpleDropdown需要的格式
    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    // 获取当前选中的值用于回显
    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;

    const that = this;

    // 如果已经打开其他筛选项，直接更新数据（组件内部会处理动画）
    if (this.data.simpleDropdownOpen) {
      // 直接更新数据，组件内部会平滑过渡
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 0, filterIndex: filterIndex }
          });
        });
    } else {
      // 直接打开
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 0, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * 显示拼房筛选选项 - 使用SimpleDropdown组件
   */
  showRoomFilterOptions: function (filterIndex) {
    const filter = this.data.roomFilters[filterIndex];

    // 如果已经打开且是同一个筛选项，直接关闭（toggle）
    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 1 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    // 将options转换为SimpleDropdown需要的格式
    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    // 获取当前选中的值用于回显
    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;

    const that = this;

    // 如果已经打开其他筛选项，直接更新数据（组件内部会处理动画）
    if (this.data.simpleDropdownOpen) {
      // 直接更新数据，组件内部会平滑过渡
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 1, filterIndex: filterIndex }
          });
        });
    } else {
      // 直接打开
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 1, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * 显示雪票筛选选项 - 使用SimpleDropdown组件
   */
  showTicketFilterOptions: function (filterIndex) {
    const filter = this.data.ticketFilters[filterIndex];

    // 如果已经打开且是同一个筛选项，直接关闭（toggle）
    if (
      this.data.simpleDropdownOpen &&
      this.data.simpleDropdownContext &&
      this.data.simpleDropdownContext.tab === 2 &&
      this.data.simpleDropdownContext.filterIndex === filterIndex
    ) {
      this.closeSimpleDropdown();
      return;
    }

    // 将options转换为SimpleDropdown需要的格式
    // 注意：时段筛选的value是字符串类型（"0", "1", "2", "3"）
    const options = filter.options.map((option, index) => ({
      id: option.value !== undefined ? option.value : index,
      name: option.text
    }));

    // 获取当前选中的值用于回显
    const selectedValue =
      filter.selectedValue !== undefined ? filter.selectedValue : null;

    const that = this;

    // 如果已经打开其他筛选项，直接更新数据（组件内部会处理动画）
    if (this.data.simpleDropdownOpen) {
      // 直接更新数据，组件内部会平滑过渡
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 2, filterIndex: filterIndex }
          });
        });
    } else {
      // 直接打开
      wx.createSelectorQuery()
        .select(".filter-section")
        .boundingClientRect()
        .exec(function (res) {
          const rect = res && res[0];
          const top = rect ? rect.top + rect.height : 100;

          that.setData({
            simpleDropdownOpen: true,
            simpleDropdownTop: top,
            simpleDropdownValue: selectedValue,
            simpleDropdownOptions: options,
            simpleDropdownContext: { tab: 2, filterIndex: filterIndex }
          });
        });
    }
  },

  /**
   * 选择拼车筛选选项
   */
  selectCarpoolFilterOption: function (filterIndex, option) {
    const filters = this.data.carpoolFilters;
    filters[filterIndex].selectedValue = option.value;
    filters[filterIndex].active = option.value !== undefined;

    // 更新筛选器显示文本
    if (option.value !== undefined) {
      filters[filterIndex].text = option.text;
    } else {
      // 恢复原始文本
      const originalTexts = ["类型", "往返", "雪场", "日期"];
      filters[filterIndex].text = originalTexts[filterIndex];
    }

    this.setData({
      carpoolFilters: filters
    });

    // 应用拼车筛选条件
    this.applyCarpoolFilters();
  },

  /**
   * 选择拼房筛选选项
   */
  selectRoomFilterOption: function (filterIndex, option) {
    const filters = this.data.roomFilters;
    filters[filterIndex].selectedValue = option.value;
    filters[filterIndex].active = option.value !== undefined;

    // 更新筛选器显示文本
    if (option.value !== undefined) {
      filters[filterIndex].text = option.text;
    } else {
      // 恢复原始文本
      const originalTexts = ["类型", "性别", "雪场", "日期"];
      filters[filterIndex].text = originalTexts[filterIndex];
    }

    this.setData({
      roomFilters: filters
    });

    // 应用拼房筛选条件
    this.applyRoomFilters();
  },

  /**
   * 选择雪票筛选选项
   */
  selectTicketFilterOption: function (filterIndex, option) {
    const filters = this.data.ticketFilters;
    filters[filterIndex].selectedValue = option.value;
    filters[filterIndex].active = option.value !== undefined;

    // 更新筛选器显示文本
    if (option.value !== undefined) {
      filters[filterIndex].text = option.text;
    } else {
      // 恢复原始文本
      const originalTexts = ["类型",'整/残', "雪场", "日期"];
      filters[filterIndex].text = originalTexts[filterIndex];
    }

    this.setData({
      ticketFilters: filters
    });

    // 应用雪票筛选条件
    this.applyTicketFilters();
  },

  /**
   * 应用拼车筛选条件
   */
  applyCarpoolFilters: function () {
    const filters = this.data.carpoolFilters;
    const carpoolRequest = {};

    // 类型筛选 - 值为undefined表示清空该字段
    carpoolRequest.type = filters[0].selectedValue;

    // 往返筛选 - 值为undefined表示清空该字段
    carpoolRequest.side = filters[1].selectedValue;

    // 雪场筛选 - 值为undefined表示清空该字段
    carpoolRequest.address = filters[2].selectedValue;

    // 日期筛选 - 值为undefined表示清空该字段
    if (filters[3].selectedValue !== undefined) {
      carpoolRequest.beginTime = this.formatDateForAPI(
        filters[3].selectedValue
      );
    } else {
      carpoolRequest.beginTime = undefined;
    }

    // 更新请求参数并重新加载数据（重置分页）
    this.updateCarpoolRequest(carpoolRequest);
  },

  /**
   * 应用拼房筛选条件
   */
  applyRoomFilters: function () {
    const filters = this.data.roomFilters;
    const roomRequest = {};

    // 类型筛选 - 值为undefined表示清空该字段
    roomRequest.type = filters[0].selectedValue;

    // 性别筛选 - 值为undefined表示清空该字段
    roomRequest.sex = filters[1].selectedValue;

    // 雪场筛选 - 值为undefined表示清空该字段
    roomRequest.address = filters[2].selectedValue;

    // 日期筛选 - 值为undefined表示清空该字段
    if (filters[3].selectedValue !== undefined) {
      roomRequest.beginTime = this.formatDateForAPI(filters[3].selectedValue);
    } else {
      roomRequest.beginTime = undefined;
    }

    // 更新请求参数并重新加载数据（重置分页）
    this.updateRoomRequest(roomRequest);
  },

  /**
   * 应用雪票筛选条件
   */
  applyTicketFilters: function () {
    const filters = this.data.ticketFilters;
    const ticketRequest = {};

    // 类型筛选 - 值为undefined表示清空该字段
    ticketRequest.type = filters[0].selectedValue;

    // 雪场筛选 - 值为undefined表示清空该字段
    ticketRequest.address = filters[2].selectedValue;

    // 日期筛选 - 值为undefined表示清空该字段
    if (filters[3].selectedValue !== undefined) {
      ticketRequest.beginTime = this.formatDateForAPI(filters[3].selectedValue);
    } else {
      ticketRequest.beginTime = undefined;
    }

    // 整/残筛选 - 值为undefined表示清空该字段
    // 注意：filters[1].selectedValue 可能是字符串 "0" 或 "1"，需要转换为数字
    if (filters[1].selectedValue !== undefined) {
      // 将字符串转换为数字，确保类型一致
      ticketRequest.isFull = typeof filters[1].selectedValue === 'string' 
        ? parseInt(filters[1].selectedValue, 10) 
        : filters[1].selectedValue;
    } else {
      ticketRequest.isFull = undefined;
    }

    // 更新请求参数并重新加载数据（重置分页）
    this.updateTicketRequest(ticketRequest);
  },

  /**
   * 格式化日期为API所需格式
   */
  formatDateForAPI: function (dateType) {
    // 如果已经是日期字符串格式（YYYY-MM-DD），直接返回
    if (typeof dateType === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(dateType)) {
      return dateType;
    }

    const today = new Date();
    let targetDate;

    switch (dateType) {
      case "today":
        targetDate = today;
        break;
      case "tomorrow":
        targetDate = new Date(today.getTime() + 24 * 60 * 60 * 1000);
        break;
      case "day_after_tomorrow":
        targetDate = new Date(today.getTime() + 2 * 24 * 60 * 60 * 1000);
        break;
      default:
        return undefined;
    }

    // 格式化为 YYYY-MM-DD
    return targetDate.toISOString().split("T")[0];
  },

  /**
   * 添加按钮点击事件
   */
  onAddClick: function () {
    console.log("添加按钮点击");
    // 直接显示抽屉，不再进行登录校验
    this.setData({
      showDrawer: true
    });
  },

  /**
   * 关闭抽屉
   */
  onCloseDrawer: function () {
    this.setData({
      showDrawer: false
    });
  },

  /**
   * TripSelector 选择变化处理
   */
  onSelectionChanged: function (e) {
    const { service, trip } = e.detail;
    console.log("选择变化:", { service, trip });

    this.setData({
      selectedService: service,
      selectedTrip: trip
    });

    // 根据选择跳转到相应页面
    this.navigateToCarpoolAdd(service, trip);
  },

  /**
   * 根据当前tab跳转到目标页面
   */
  navigateToTargetPage: function (service, trip) {
    const currentConfig = this.data.popupConfigs[this.data.activeTab];
    const targetPage = currentConfig.targetPage;

    console.log("跳转配置:", {
      activeTab: this.data.activeTab,
      service,
      trip,
      targetPage
    });

    if (targetPage === "carpoolAdd") {
      // 拼车页面
      const side = trip === "outbound" ? "0" : "1";
      const type = service === "car-find-people" ? "0" : "1";
      const url = `/pages/carpoolAdd/carpoolAdd?side=${side}&type=${type}`;

      wx.navigateTo({
        url: url,
        success: function () {
          console.log("跳转到拼车发布页面成功", { service, trip, side, type });
        },
        fail: function () {
          console.log("跳转到拼车发布页面失败");
          wx.showToast({
            title: "页面跳转失败",
            icon: "none"
          });
        }
      });
    } else if (targetPage === "roomSharingAdd") {
      // 拼房页面
      const sex = trip === "male" ? "0" : "1";
      const type = service === "room-find-people" ? "0" : "1";
      const url = `/pages/roomSharingAdd/roomSharingAdd?sex=${sex}&type=${type}`;

      wx.navigateTo({
        url: url,
        success: function () {
          console.log("跳转到拼房发布页面成功", { service, trip, sex, type });
        },
        fail: function () {
          console.log("跳转到拼房发布页面失败");
          wx.showToast({
            title: "页面跳转失败",
            icon: "none"
          });
        }
      });
    } else if (targetPage === "ticketAdd") {
      // 雪票页面
      const ticketType = trip === "single-day" ? "0" : "1";
      const tradeType = service === "ticket-sell" ? "1" : "0";
      const url = `/pages/ticketAdd/ticketAdd?type=${tradeType}&ticket=${ticketType}`;

      wx.navigateTo({
        url: url,
        success: function () {
          console.log("跳转到雪票发布页面成功", {
            service,
            trip,
            tradeType,
            ticketType
          });
        },
        fail: function () {
          console.log("跳转到雪票发布页面失败");
          wx.showToast({
            title: "页面跳转失败",
            icon: "none"
          });
        }
      });
    }
  },

  /**
   * 跳转到拼车发布页面 (保留兼容性)
   */
  navigateToCarpoolAdd: function (service, trip) {
    const side = trip === "outbound" ? "0" : "1";
    const type = service === "car-find-people" ? "0" : "1";

    const url = `/pages/carpoolAdd/carpoolAdd?side=${side}&type=${type}`;

    wx.navigateTo({
      url: url,
      success: function () {
        console.log("跳转到拼车发布页面成功", { service, trip, side, type });
      },
      fail: function () {
        console.log("跳转到拼车发布页面失败");
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 选择服务类型
   */
  selectService: function (e) {
    const serviceType = e.currentTarget.dataset.service;
    console.log("选择服务类型:", serviceType);

    this.setData({
      selectedService: serviceType
    });
  },

  /**
   * TripSelector 选择行程类型 (保留兼容性)
   */
  selectTrip: function (e) {
    const tripType = e.currentTarget.dataset.trip;
    console.log("选择行程类型:", tripType);

    this.setData({
      selectedTrip: tripType
    });

    // 根据当前tab跳转到不同页面
    this.navigateToTargetPage(this.data.selectedService, tripType);

    // 关闭抽屉
    this.setData({
      showDrawer: false
    });
  },

  /**
   * 抽屉选项点击事件
   */
  onDrawerOptionClick: function (e) {
    const option = e.currentTarget.dataset.option;
    console.log("抽屉选项点击:", option);

    // 关闭抽屉
    this.setData({
      showDrawer: false
    });

    // 根据选项执行相应操作
    if (option === "carpool") {
      wx.navigateTo({
        url: "/pages/carpoolAdd/carpoolAdd",
        success: function () {
          console.log("跳转到拼车信息新增页面成功");
        },
        fail: function () {
          console.log("跳转到拼车信息新增页面失败");
          wx.showToast({
            title: "页面跳转失败",
            icon: "none"
          });
        }
      });
    } else if (option === "room") {
      wx.showToast({
        title: "拼房功能开发中",
        icon: "none",
        duration: 2000
      });
    } else if (option === "ticket") {
      wx.showToast({
        title: "雪票功能开发中",
        icon: "none",
        duration: 2000
      });
    }
  },

  /**
   * 底部导航点击事件
   */
  onNavClick: function (e) {
    const index = e.currentTarget.dataset.index;
    console.log("导航点击:", this.data.navItems[index].name);

    wx.showToast({
      title: this.data.navItems[index].name + "功能开发中",
      icon: "none",
      duration: 2000
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log("Home页面渲染完成");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("Home页面显示");

    // 页面显示时刷新轮播图数据
    this.loadBannerList();

    // // 更新tabbar选中状态
    // this.setData({
    //   tabbarActive: 0
    // });

    // // 检查是否从登录页面返回，如果是则显示抽屉
    // this.checkLoginReturn();

    // // 页面可见时刷新当前tab的数据（仅在页面已初始化后刷新，避免首次加载时重复请求）
    // if (this.data.isPageInitialized) {
    //   const activeTab = this.data.activeTab;
    //   if (activeTab === 0) {
    //     // 拼车tab - 刷新数据
    //     this.loadCarpoolData(false);
    //   } else if (activeTab === 1) {
    //     // 拼房tab - 刷新数据
    //     this.loadRoomData(false);
    //   } else if (activeTab === 2) {
    //     // 雪票tab - 刷新数据
    //     this.loadSnowTicketData(false);
    //   }
    // }
  },

  /**
   * 测试登录API（调试用）
   */
  testLoginApi: function () {
    console.log("开始测试登录API...");
    util.testLoginApi();
  },

  /**
   * 测试登录校验函数（调试用）
   */
  testLoginCheck: function () {
    console.log("测试登录校验函数...");
    console.log(
      "util.executeWithLoginCheck 是否存在:",
      typeof util.executeWithLoginCheck
    );

    if (typeof util.executeWithLoginCheck === "function") {
      console.log("✅ executeWithLoginCheck 函数存在");
      util.executeWithLoginCheck(
        () => {
          console.log("✅ 登录校验测试成功 - 用户已登录");
          wx.showToast({
            title: "登录校验测试成功",
            icon: "success"
          });
        },
        "测试登录校验功能，是否立即登录？",
        "/pages/home/home"
      );
    } else {
      console.error("❌ executeWithLoginCheck 函数不存在");
      wx.showToast({
        title: "函数不存在",
        icon: "error"
      });
    }
  },

  /**
   * 测试跳转到拼车详情页（调试用）
   */
  testNavigateToDetail: function () {
    console.log("测试跳转到拼车详情页...");

    // 使用第一个卡片的ID进行测试
    const testId = "demo_001";
    const url = `/pages/carpoolDetail/carpoolDetail?id=${testId}`;

    wx.navigateTo({
      url: url,
      success: function () {
        console.log("✅ 测试跳转成功:", url);
      },
      fail: function (err) {
        console.error("❌ 测试跳转失败:", err);
        wx.showToast({
          title: "跳转失败",
          icon: "error"
        });
      }
    });
  },

  /**
   * 拼车卡片点击事件
   */
  onCardClick: function (e) {
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.carpoolCards[index];

    console.log("点击拼车卡片:", cardData);

    if (!cardData || !cardData.id) {
      console.error("拼车卡片数据不完整:", cardData);
      wx.showToast({
        title: "数据错误",
        icon: "none"
      });
      return;
    }

    // 跳转到拼车详情页
    const url = `/pages/carpoolDetail/carpoolDetail?id=${cardData.id}`;

    wx.navigateTo({
      url: url,
      success: function () {
        console.log("跳转到拼车详情页成功:", url);
      },
      fail: function (err) {
        console.error("跳转到拼车详情页失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 拼房卡片点击事件
   */
  onRoomCardClick: function (e) {
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.roomSharingCards[index];

    console.log("点击拼房卡片:", cardData);

    if (!cardData || !cardData.id) {
      console.error("拼房卡片数据不完整:", cardData);
      wx.showToast({
        title: "数据错误",
        icon: "none"
      });
      return;
    }

    // 跳转到拼房详情页
    const url = `/pages/roomSharingDetail/roomSharingDetail?id=${cardData.id}`;

    wx.navigateTo({
      url: url,
      success: function () {
        console.log("跳转到拼房详情页成功:", url);
      },
      fail: function (err) {
        console.error("跳转到拼房详情页失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 雪票卡片点击事件
   */
  onSnowTicketCardClick: function (e) {
    const index = e.currentTarget.dataset.index;
    const cardData = this.data.snowTicketCards[index];

    console.log("点击雪票卡片:", cardData);

    if (!cardData || !cardData.id) {
      console.error("雪票卡片数据不完整:", cardData);
      wx.showToast({
        title: "数据错误",
        icon: "none"
      });
      return;
    }

    // 跳转到雪票详情页
    const url = `/pages/ticketDetail/ticketDetail?id=${cardData.id}`;

    wx.navigateTo({
      url: url,
      success: function () {
        console.log("跳转到雪票详情页成功:", url);
      },
      fail: function (err) {
        console.error("跳转到雪票详情页失败:", err);
        wx.showToast({
          title: "页面跳转失败",
          icon: "none"
        });
      }
    });
  },

  /**
   * 检查是否从登录页面返回
   */
  checkLoginReturn: function () {
    const that = this;
    const userInfo = wx.getStorageSync("userInfo");
    const token = wx.getStorageSync("token");
    const navUrl = wx.getStorageSync("navUrl");

    // 如果用户已登录且当前页面是目标页面，则显示抽屉
    if (userInfo && token && navUrl === "/pages/home/home") {
      console.log("用户登录成功返回，显示抽屉");
      // 清除导航URL
      wx.removeStorageSync("navUrl");
      // 显示抽屉
      that.setData({
        showDrawer: true
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("Home页面隐藏");
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("Home页面卸载");
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    console.log("用户下拉刷新，当前tab:", this.data.activeTab);

    const activeTab = this.data.activeTab;
    const that = this;

    // 刷新轮播图数据
    const bannerPromise = this.loadBannerList();

    // 刷新当前tab的数据
    if (activeTab === 0) {
      // 重新加载拼车数据（重置分页）
      this.loadCarpoolData(false);
    } else if (activeTab === 1) {
      // 重新加载拼房数据（重置分页）
      this.loadRoomData(false);
    } else if (activeTab === 2) {
      // 重新加载雪票数据（重置分页）
      this.loadSnowTicketData(false);
    }

    // 等待轮播图数据加载完成后再停止下拉刷新
    // 其他tab数据会在各自的方法中处理，这里主要等待轮播图
    bannerPromise
      .then(function () {
        // 停止下拉刷新
        wx.stopPullDownRefresh();
      })
      .catch(function (err) {
        console.error("下拉刷新轮播图数据加载失败:", err);
        // 即使失败也要停止下拉刷新
        wx.stopPullDownRefresh();
      });
  },

  /**
   * content-area scroll-view 滚动到底部事件的处理函数
   */
  onContentScrollToLower: function () {
    console.log("content-area滚动到底部，当前tab:", this.data.activeTab);

    const activeTab = this.data.activeTab;

    if (activeTab === 0) {
      // 拼车tab - 加载更多
      if (this.data.carpoolHasMore && !this.data.loading) {
        // 页码在loadCarpoolData函数内部处理，这里直接调用
        this.loadCarpoolData(true);
      }
    } else if (activeTab === 1) {
      // 拼房tab - 加载更多
      if (this.data.roomHasMore && !this.data.loading) {
        // 页码在loadRoomData函数内部处理，这里直接调用
        this.loadRoomData(true);
      }
    } else if (activeTab === 2) {
      // 雪票tab - 加载更多
      if (this.data.ticketHasMore && !this.data.loading) {
        // 页码在loadSnowTicketData函数内部处理，这里直接调用
        this.loadSnowTicketData(true);
      }
    }
  },

  /**
   * 页面上拉触底事件的处理函数（保留作为备用）
   */
  onReachBottom: function () {
    console.log("页面触底，当前tab:", this.data.activeTab);

    const activeTab = this.data.activeTab;

    if (activeTab === 0) {
      // 拼车tab - 加载更多
      if (this.data.carpoolHasMore && !this.data.loading) {
        // 页码在loadCarpoolData函数内部处理，这里直接调用
        this.loadCarpoolData(true);
      }
    } else if (activeTab === 1) {
      // 拼房tab - 加载更多
      if (this.data.roomHasMore && !this.data.loading) {
        // 页码在loadRoomData函数内部处理，这里直接调用
        this.loadRoomData(true);
      }
    } else if (activeTab === 2) {
      // 雪票tab - 加载更多
      if (this.data.ticketHasMore && !this.data.loading) {
        // 页码在loadSnowTicketData函数内部处理，这里直接调用
        this.loadSnowTicketData(true);
      }
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: "拼车拼房拼雪票，加入俱乐部社群更有专属福利！",
      path: "/pages/home/home"
    };
  }
});
